package com.lw.service.impl;

import com.lw.entity.TbInterface;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.lw.entity.TbUserInterface;
import com.lw.mapper.TbUserInterfaceMapper;
import com.lw.service.TbUserInterfaceService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static cn.dev33.satoken.SaManager.log;

/**
 * 服务层实现。
 *
 * @author lw
 * @since 2025年04月29日 17:50:05
 */
@Service
public class TbUserInterfaceServiceImpl extends ServiceImpl<TbUserInterfaceMapper, TbUserInterface> implements TbUserInterfaceService {


    @Override
    @Transactional
    public int updateInterfaceByUserId(Integer id, List<TbInterface> tbInterfaceList) {
        //先删除用户id相关接口记录，再新增
        QueryWrapper tbUserInterfaceQueryWrapper = new QueryWrapper();
        tbUserInterfaceQueryWrapper.eq(TbUserInterface::getUserId, id);
        boolean remove = remove(tbUserInterfaceQueryWrapper);
        log.info("删除用户接口结果：{}", remove);
        if (tbInterfaceList == null || tbInterfaceList.isEmpty()) {
            return 1;
        }

        //新增
        List<TbUserInterface> userInterfaces = new ArrayList<>();
        for (TbInterface tbInterface : tbInterfaceList) {
            TbUserInterface tbUserInterface = new TbUserInterface();
            tbUserInterface.setUserId(id);
            tbUserInterface.setInterfaceId(tbInterface.getId());
            userInterfaces.add(tbUserInterface);
        }
        boolean b = saveBatch(userInterfaces);
        log.info("新增用户接口结果：{}", b);
        return userInterfaces.size() + 1;
    }
}
